package com.order.service;

import com.order.common.PageQuery;
import com.order.dto.CreateOrderRequest;
import com.order.entity.OrderInfo;
import com.order.mapper.OrderInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单服务类
 */
@Service
public class OrderService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 分页查询订单列表
     */
    public List<OrderInfo> getOrderList(PageQuery pageQuery, Integer status, Long categoryId, Long userId, Integer roleType) {
        int offset = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        return orderInfoMapper.selectOrderList(offset, pageQuery.getPageSize(), status, categoryId, userId, roleType);
    }

    /**
     * 统计订单数量
     */
    public Long countOrders(PageQuery pageQuery, Integer status, Long categoryId, Long userId, Integer roleType) {
        return orderInfoMapper.countOrders(status, categoryId, userId, roleType);
    }

    /**
     * 根据ID获取订单
     */
    public OrderInfo getOrderById(Long id) {
        return orderInfoMapper.selectById(id);
    }

    /**
     * 创建订单
     */
    @Transactional
    public void createOrder(CreateOrderRequest request, Long userId) {
        OrderInfo order = new OrderInfo();
        order.setUserId(userId);
        order.setCategoryId(request.getCategoryId());
        order.setTitle(request.getTitle());
        order.setDescription(request.getDescription());
        order.setBudget(request.getBudget());
        order.setDeadline(request.getDeadline());
        order.setStatus(1); // 待接单
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        // 生成订单号
        String orderNo = "ORD" + System.currentTimeMillis();
        order.setOrderNo(orderNo);
        
        orderInfoMapper.insert(order);
    }

    /**
     * 技术员接单
     */
    @Transactional
    public void acceptOrder(Long orderId, Long techId) {
        OrderInfo order = orderInfoMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (order.getStatus() != 1) {
            throw new RuntimeException("订单状态不允许接单");
        }
        
        order.setTechId(techId);
        order.setStatus(2); // 进行中
        order.setAcceptTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        orderInfoMapper.updateById(order);
    }

    /**
     * 派单员指派订单
     */
    @Transactional
    public void assignOrder(Long orderId, Long techId, Long dispatcherId) {
        OrderInfo order = orderInfoMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (order.getStatus() != 1) {
            throw new RuntimeException("订单状态不允许指派");
        }
        
        order.setTechId(techId);
        order.setDispatcherId(dispatcherId);
        order.setStatus(2); // 进行中
        order.setAcceptTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        orderInfoMapper.updateById(order);
    }

    /**
     * 完成订单
     */
    @Transactional
    public void completeOrder(Long orderId, Long userId, Integer roleType) {
        OrderInfo order = orderInfoMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 技术员提交完成
        if (roleType == 4 && order.getTechId().equals(userId)) {
            if (order.getStatus() != 2) {
                throw new RuntimeException("订单状态不允许完成");
            }
            order.setStatus(3); // 待验收
            order.setCompleteTime(LocalDateTime.now());
        }
        // 用户验收完成
        else if (roleType == 3 && order.getUserId().equals(userId)) {
            if (order.getStatus() != 3) {
                throw new RuntimeException("订单状态不允许验收");
            }
            order.setStatus(4); // 已完成
            order.setFinishTime(LocalDateTime.now());
        }
        else {
            throw new RuntimeException("无权限操作此订单");
        }
        
        order.setUpdateTime(LocalDateTime.now());
        orderInfoMapper.updateById(order);
    }

    /**
     * 取消订单
     */
    @Transactional
    public void cancelOrder(Long orderId, Long userId, Integer roleType) {
        OrderInfo order = orderInfoMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 只有订单发布者或管理员可以取消订单
        if (roleType != 1 && !order.getUserId().equals(userId)) {
            throw new RuntimeException("无权限取消此订单");
        }
        
        if (order.getStatus() == 4 || order.getStatus() == 5) {
            throw new RuntimeException("订单已完成或已取消，无法取消");
        }
        
        order.setStatus(5); // 已取消
        order.setCancelTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        orderInfoMapper.updateById(order);
    }
}